﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ServerPlatform.Exceptions
{
    public static class ExceptionManager
    {
        public static ApplicationException Manage(Exception exc)
        {
            return Manage(exc, false);
        }
        public static ApplicationException Manage(Exception exc, bool throwException)
        {
            ApplicationException converted = null;
            if (exc is BusinessException)
            {
                converted = (BusinessException)exc;
            }
            else if (exc is TechnicalException)
            {
                converted = (TechnicalException)exc;
            }
            else
            {
                converted = new TechnicalException(exc.Message, exc);
                return converted;
            }
            if (!(converted is BusinessException))
                LogException(converted);
            if (throwException)
                throw converted;
            return converted;
        }

        private static void LogException(ApplicationException converted)
        {
            string data = GetExceptionData(converted);   
        }

        private static string GetExceptionData(Exception exc)
        {
            Exception e = exc;
            StringBuilder sb = new StringBuilder();
            while (e != null)
            {
                sb.Append(GetExceptionInnerData(e));
                e = e.InnerException;
            }
            return sb.ToString();
        }

        private static string GetExceptionInnerData(Exception e)
        {
            return string.Format("Message:{0}\nStackTrace:{1}\nUser:{2}", e.Message, e.StackTrace, Thread.CurrentPrincipal.Identity.Name);
        }

        
    }
}
